/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chat;

import fsktms.IMessage;
import fsktms.messagemanager.IMessageListener;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Collection;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author salm
 */
public class ChatClient implements IMessageListener
{
    private Collection<IChatMessageListener> messageListeners = new LinkedList();
    
    @Override
    public void onHasNewMessage(final IMessage msg)
    {
        (new Thread()
        {
            @Override
            public void run()
            {
                processMessage(msg);
            }
        }).start();
    }
    
    
    private void processMessage(IMessage msg)
    {
        try (ObjectInputStream oIS = new ObjectInputStream(new ByteArrayInputStream(msg.getData())))
        {
            ChatMessage chatMsg = (ChatMessage) oIS.readObject();
            if (chatMsg != null)
            {
                for (IChatMessageListener listener : this.messageListeners)
                {
                    listener.onHasChatMessage(chatMsg);
                }
            }
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @return the messageListeners
     */
    public Collection<IChatMessageListener> getMessageListeners() {
        return messageListeners;
    }
}
